package dk.mirasola.systemtraining.bridgewidgets.client.ui.editor;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;


public class GroupNameEditor extends Composite implements LeafValueEditor<String> {
    interface GroupNameEditorUIBinder extends UiBinder<Widget, GroupNameEditor> {
    }

    private static GroupNameEditorUIBinder uiBinder = GWT.create(GroupNameEditorUIBinder.class);

    @UiField
    TextBox nameEditor;

    public GroupNameEditor() {
        initWidget(uiBinder.createAndBindUi(this));

        nameEditor.addKeyUpHandler(new KeyUpHandler() {
            @Override
            public void onKeyUp(KeyUpEvent event) {
                if (nameEditor.getValue().length() == 0) {
                    nameEditor.addStyleDependentName("invalid");
                } else {
                    nameEditor.removeStyleDependentName("invalid");
                }
            }
        });
    }

    @Override
    public void setValue(String value) {
        if (value == null) {
            throw new NullPointerException();
        }
        nameEditor.setValue(value);
    }

    @Override
    public String getValue() {
        if (nameEditor.getValue().length() == 0) {
            return "#missing#";
        }
        return nameEditor.getValue();
    }
}
